<template>
  <div class="main">
    <el-affix :offset="0">
      <ComAffix />
    </el-affix>
    <div class="bode">
      <div class="page">
        <div class="side">
          <div class="message-title">
            <el-icon><Setting /></el-icon>
            <span class="center">账号设置</span>
          </div>

          <el-menu default-active="3" router>
            <el-menu-item index="/set">
              <template #title>
                <el-icon><Avatar /></el-icon>
                <span>个人中心</span>
              </template>
            </el-menu-item>

            <el-menu-item index="/user">
              <template #title>
                <el-icon><HomeFilled /></el-icon>
                <span>个人主页</span>
              </template>
            </el-menu-item>

            <el-menu-item index="/safe">
              <template #title>
                <el-icon><Key /></el-icon>
                <span>密码设置</span>
              </template>
            </el-menu-item>
          </el-menu>
        </div>

        <div class="change-avatar">
          <!-- 密码验证卡片 -->
          <div class="password-card">
            <!-- 原密码验证区域 -->
            <div class="verify-section" :class="{ 'verified': isVerified }">
              <h3 class="section-title">验证身份</h3>
              <p class="section-desc">请输入原密码进行验证，以确保账号安全</p>

              <div class="input-group">
                <el-input
                  v-model="oldPassword"
                  type="password"
                  placeholder="请输入原密码"
                  show-password
                  :disabled="isVerified"
                />

                <el-button
                  type="primary"
                  @click="verifyOldPassword"
                  :loading="isLoading"
                  :disabled="isVerified"
                  class="verify-btn"
                >
                  验证
                </el-button>
              </div>
            </div>

            <!-- 新密码设置区域（验证通过后显示） -->
            <div class="reset-section" v-if="isVerified">
              <h3 class="section-title">设置新密码</h3>

              <div class="input-group">
                <el-input
                  v-model="newPassword"
                  type="password"
                  placeholder="请输入新密码"
                  show-password
                  :disabled="!isVerified"
                />
                <span class="input-hint">请输入新密码，不少于六位</span>
              </div>

              <div class="input-group">
                <el-input
                  v-model="confirmPassword"
                  type="password"
                  placeholder="请再次输入密码"
                  show-password
                  :disabled="!isVerified"
                />
                <span class="input-hint">请再次输入密码进行确认</span>
              </div>

              <div class="action-group">
                <el-button
                  type="primary"
                  @click="submitNewPassword"
                  :disabled="!isVerified || !canSubmit"
                  class="submit-btn"
                >
                  提交修改
                </el-button>

                <el-button
                  type="text"
                  @click="cancelReset"
                  class="cancel-btn"
                >
                  取消
                </el-button>
              </div>
            </div>
          </div>
        </div>
          </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import ComAffix from "@/components/ComAffix.vue";
import { ElMessage } from 'element-plus';
import {
  Avatar,
  HomeFilled,
  Key,
  Setting
} from '@element-plus/icons-vue';
import {useUserStore} from "@/stores/index.js";
import {checkPassword, updateUserInfoService, userGetPassword} from "@/api/User.js";

// 密码数据绑定
const oldPassword = ref('');
const newPassword = ref('');
const confirmPassword = ref('');
const useStore = useUserStore();

// 状态管理
const isVerified = ref(false);
const isLoading = ref(false);

const canSubmit = computed(() => {
  return newPassword.value &&
    confirmPassword.value &&
    newPassword.value === confirmPassword.value &&
    newPassword.value.length >= 6;
});

const verifyOldPassword = async () => {
  if (!oldPassword.value) {
    ElMessage.warning('请输入原密码');
    return;
  }

  isLoading.value = true;
  try {
    // 正确获取API响应
    const response = await userGetPassword(useStore.user.id);

    // 从响应对象中提取实际密码
    const actualPassword = response.data;

    console.log('API返回的密码:', actualPassword.data);
    console.log('用户输入的密码:', oldPassword.value);
const check = await checkPassword(oldPassword.value,actualPassword.data);
    // 实际比较密码
    if (check) {
      isVerified.value = true;
      ElMessage.success('原密码验证通过');
    } else {
      ElMessage.error('原密码不正确，请重新输入');
    }
  } catch (error) {
    const response = await userGetPassword(useStore.user.id);
    const actualPassword = response.data;

    console.log('API返回的密码:', actualPassword.data);
    console.log('用户输入的密码:', oldPassword.value);
    const check = await checkMessage(oldPassword.value,actualPassword.data);
    // 这里 error 是完整的响应对象，我们从中提取密码
    if (error.data) {
      if (check) {
        isVerified.value = true;
        ElMessage.success('原密码验证通过');
      } else {
        ElMessage.error('原密码不正确，请重新输入');
      }
    } else {
      ElMessage.error('验证失败，请稍后重试');
      console.error("密码验证错误:", error);
    }
  } finally {
    isLoading.value = false;
  }
};

const submitNewPassword = async () => {
  if (newPassword.value.length < 6) {
    ElMessage.warning('新密码长度不能少于6位');
    return;
  }

  if (newPassword.value === oldPassword.value) {
    ElMessage.warning('新密码不能与原密码相同');
    return;
  }

  isLoading.value = true;
  try {
    // 这里应该是实际更新密码的API调用
    const updateData = {
     password: newPassword.value
    };
    const userId = useStore.user.id;
    const updatedUser = await updateUserInfoService(userId, updateData);
    ElMessage.success('密码修改成功');

    // 重置表单
    oldPassword.value = '';
    newPassword.value = '';
    confirmPassword.value = '';
    isVerified.value = false;
  } catch (error) {
    ElMessage.error('密码修改失败，请稍后重试');
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped lang="scss">
.main {
  display: grid;
  background-color: #f6f3f3;
}

.bode {
  display: grid;
  justify-content: center;
  margin-top: 40px;
}

.page {
  display: flex;
  justify-content: center;
  width: 100%; /* 占满父容器 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  align-content: center;
  background-color: white;
  .side {
    flex: 0 0 20%; /* 占 30% 宽度 */
  }
  .change-avatar{
    flex: 1; /* 占剩余 70% 宽度 */
    display: grid;
    width: 800px;
    min-height: 500px;
    justify-content: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    gap: 1px;
    .password-card {

      width: 100%;
      max-width: 500px;
      padding: 30px;
      border-radius: 12px;
      background-color: #f9fafc;
      border: 1px solid #f0f0f0;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);
    }

    // 区域标题
    .section-title {
      font-size: 18px;
      font-weight: 500;
      color: #303133;
      margin: 0 0 10px 0;
    }

    // 区域描述
    .section-desc {
      font-size: 14px;
      color: #606266;
      margin: 0 0 25px 0;
      line-height: 1.5;
    }

    // 输入组容器
    .input-group {
      display: flex;
      flex-direction: column;
      gap: 8px;
      margin-bottom: 22px;

      .el-input {
        width: 100%;
        height: 42px;
        border-radius: 6px;
      }

      // 输入提示文本
      .input-hint {
        font-size: 12px;
        color: #909399;
        padding-left: 2px;
        line-height: 1.4;
      }
    }

    // 验证区域特殊样式
    .verify-section {
      padding-bottom: 25px;
      border-bottom: 1px dashed #f0f0f0;

      &.verified {
        opacity: 0.7; // 验证通过后降低透明度，突出新密码区域
      }

      .verify-btn {
        margin-top: 8px;
        width: 100%;
        height: 42px;
      }
    }

    // 重置密码区域
    .reset-section {
      height: 500px;
      padding-top: 25px;
    }

    // 操作按钮组
    .action-group {
      display: flex;
      gap: 15px;
      margin-top: 10px;

      .submit-btn {
        flex: 1;
        height: 42px;
      }

      .cancel-btn {
        color: #606266;
        padding: 0 15px;

        &:hover {
          color: #303133;
          background-color: #f5f7fa;
        }
      }
    }
  }

  // 响应式适配
  @media (max-width: 768px) {
    .change-avatar {
      padding: 20px 15px;
    }

    .password-card {
      padding: 20px 15px;
    }

    .input-group,
    .action-group {
      width: 100%;
    }
  }
}

.el-menu-item {
  height: 56px;
  line-height: 56px;
  border-top: none;
  border-left: 3px solid transparent;
  transition: all 0.2s ease;

  &:hover {
    background-color: #d1def3;
    border-left-color: #a2bac9;
  }

  &.is-active {
    background-color: #f5f7fa;
    border-left-color: #409eff;
    color: #409eff;

    .el-icon {
      color: #409eff;
    }
  }

  .el-icon {
    font-size: 16px;
    margin-right: 12px;
    color: #faccd1;
  }
}
// 账号设置标题样式（带图标和文字排版）
.message-title {
  // 布局与对齐
  display: flex;
  align-items: center;
  padding: 18px 24px; // 上下内边距稍大，增强区域感
  gap: 12px; // 图标与文字间距

  // 图标样式
  .el-icon {
    font-size: 20px; // 图标尺寸适中
    color: #409eff; // 主题色图标，突出标题
    width: 24px;
    height: 24px;
    flex-shrink: 0; // 防止图标被压缩
  }

  // 文字样式
  .center {
    font-size: 18px;
    font-weight: 500; // 中等加粗，突出层级
    color: #303133; // 深灰色文字，提升可读性
    line-height: 1.4;
  }

  // 装饰与分隔
  border-bottom: 1px solid #f0f0f0; // 底部浅色边框，分隔区域
  background-color: #fcfcfc; // 轻微背景色，与内容区区分
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02); // 顶部微阴影，增强层次感
}

// 响应式适配
@media (max-width: 768px) {
  .message-title {
    padding: 14px 16px; // 小屏幕减少内边距
    gap: 10px;

    .el-icon {
      font-size: 18px;
    }

    .center {
      font-size: 16px;
    }
  }
}
.center {
  font-size: 20px;
}

.text {
  font-size: 14px;
}

.box-card {
  width: 480px;
}

.badge-container {
  position: relative;
}

span {
  justify-content: center;
  display: flex;}

.el-input{
  width: 30px;
  height: 30px;
}
.el-button{
  width:100px;
}
.primary-password{
  display: grid;
  gap:10px;
}
.edit-password{
  display: grid;
  grid-template-columns: 200px auto; /* 第一列宽度为 240px（输入框宽度），第二列自适应 */
  gap: 5px; /* 垂直间距 10px，水平间距 15px */
  align-items: center; /* 垂直居中对齐 */
}
.newp{
  color: indianred;
}
</style>
